<?php
class ImagesController extends AppController {
	var $name = 'Images';

    public function upload ($type, $up='', $album_id='') {
        if ($type && $up) {
            Configure::write('debug', 0);

            $imageWidth   = 580;
            $imageHeight  = 380;
            $imageWidth2  = 618;
            $imageHeight2 = 380;
            $thumbWidth   = 180;
            $thumbWidth2  = 194;
            $thumbHeight2 = 155;
            $sizeLimit    = 2097152;

            switch ($type) {
                case 'events':
                    $saveDir = WWW_ROOT.'img'.DS.'events'.DS;
                break;
                case 'gallery':
                    $saveDir = WWW_ROOT.'img'.DS.'gallery'.DS;
                break;
                case 'products':
                    $saveDir = WWW_ROOT.'img'.DS.'products'.DS;
                break;
            }

            if (isset($_FILES['Filedata']['name'])) {
                $timestamp = time();
                $extension = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);
                $filename  = $timestamp.'.'.strtolower($extension);
                $filesize  = $_FILES['Filedata']['size'];
                $temp_path = $_FILES['Filedata']['tmp_name'];
                $save_path = $saveDir.$filename;
                $album_id  = empty($album_id) ? 0 : $album_id;
                $hash_str  = md5_file($temp_path);

                if (!is_uploaded_file($temp_path) || ($filesize > $sizeLimit) ) {
                    $this->response(array(
                        'status' => '0',
                        'error'  => __('Please upload only files smaller than 2Mb!', true)
                    ));
                    return;
                }
                if (!$size = @getimagesize($temp_path)) {
                    $this->response(array(
                        'status' => '0',
                        'error'  => __('Please upload only images, no other files are supported.', true)
                    ));
                    return;
                }

                list($width, $height, $mime,) = $size;

                if (!in_array($mime, array(1, 2, 3, 7, 8))) { // invalid image mime type
                    $this->response(array(
                        'status' => '0',
                        'error'  => __('Please upload only images of type JPEG, GIF or PNG.', true)
                    ));
                    return;
                }
                if ($width < 25 || $height < 25) { // uploaded image is too small
                    $this->response(array(
                        'status' => '0',
                        'error'  => __('Please upload an image bigger than 25px.', true)
                    ));
                    return;
                }

                switch ($mime) {
                    case 1:
                        $_FILES['Filedata']['type'] = 'image/gif';
                    break;
                    case 2:
                        $_FILES['Filedata']['type'] = 'image/jpg';
                    break;
                    case 3:
                        $_FILES['Filedata']['type'] = 'image/png';
                    break;
                    case 6:
                        $_FILES['Filedata']['type'] = 'image/bmp';
                    break;
                }

                App::import('Vendor', 'ImageClass', array('file'=>'image.class.php'));

                // default thumbnail
                $img                     = new upload($_FILES['Filedata']);
                $img->file_max_size      = $sizeLimit;
                $img->mime_check         = false;
                $img->file_new_name_body = 's_'.$timestamp;
                $img->image_min_width    = 25;
                $img->image_min_height   = 25;
                $img->image_resize       = true;
                $img->image_x            = $thumbWidth;
                $img->image_ratio_y      = true;
                $img->Process($saveDir);

                if ($img->processed) {
                    $thumbnail = $img->file_dst_name;
                } else {
                    $this->response(array(
                        'status' => '0',
                        'error'  => __($img->error, true)
                    ));
                    return;
                }

                // display thumbnail
                $img->file_new_name_body = 't_'.$timestamp;
                $img->image_resize       = true;
                $img->image_x            = $thumbWidth2;
                $img->image_y            = $thumbHeight2;
                $img->image_ratio_crop   = true;
                $img->Process($saveDir);

                if (!$img->processed) {
                    $this->response(array(
                        'status' => '0',
                        'error'  => __($img->error, true)
                    ));
                    return;
                }

                // display banner
                $img->file_new_name_body = 'l_'.$timestamp;
                $img->image_resize       = true;
                $img->image_x            = $imageWidth2;
                $img->image_y            = $imageHeight2;
                $img->image_ratio_crop   = true;
                $img->Process($saveDir);

                if (!$img->processed) {
                    $this->response(array(
                        'status' => '0',
                        'error'  => __($img->error, true)
                    ));
                    return;
                }

                if ($width > $imageWidth || $height > $imageHeight) { // resize image that larger than require size
                    $img->file_new_name_body = $timestamp;
                    $img->image_resize       = true;
                    $img->image_x            = $imageWidth;
                    $img->image_y            = $imageHeight;
                    $img->image_ratio        = true;
                    $img->Process($saveDir);

                    if ($img->processed) {
                        $filename = $img->file_dst_name;
                    } else {
                        $this->response(array(
                            'status' => '0',
                            'error'  => __($img->error, true)
                        ));
                        return;
                    }

                    list($width, $height, ,) = @getimagesize($save_path);
                    $filesize = filesize($save_path);
                } else {
                    move_uploaded_file($temp_path, $save_path);
                }
                $img->Clean();

                $data['Image'] = array('album_id' => $album_id,
                                       'filename' => $filename);
                $this->Image->save($data);

                if ($album_id) {
                    $this->loadModel('Album');
                    $this->Album->id = $album_id;
                    $cover = $this->Album->field('image_id');
                    if (!$cover) {
                        $this->Album->saveField('image_id', $this->Image->id);
                    }
                }

                $json = array(
                    'status' => '1',
                    'id'     => $this->Image->id,
                    'name'   => $_FILES['Filedata']['name'],
                    'hash'   => $hash_str,
                    'thumb'  => $type.'/'.$thumbnail
                );
                if (is_array($size) && count($size) > 2) {
                    $json['width']  = $width;
                    $json['height'] = $height;
                    $json['mime']   = $size['mime'];
                }
            } else {
                $json = array(
                    'status' => '0',
                    'error'  => __('No file selected for upload', true)
                );
            }

            $this->response($json);
        } else if ($type && !$up) {
            if ($album_id) {
                $data = $this->Image->find('all', array(
                    'conditions' => array('album_id' => $album_id),
                    'recursive'  => -1,
                    'fields'     => array('id', 'filename', 'title', 'description'),
                    'order'      => array('id')
                ));

                $this->loadModel('Album');
                $this->Album->id = $album_id;

                $this->set('data', $data);
                $this->set('cover', $this->Album->field('image_id'));
            }

            $this->stylesheet  = am($this->stylesheet, 'FancyUpload/FancyUpload');
            $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js', 'FancyUpload/Swiff.Uploader', 'FancyUpload/Fx.ProgressBar', 'FancyUpload/FancyUpload2', $type);
            $this->set('uploadURL', $this->base.'/images/upload/'.$type.'/up/'.$album_id);
            $this->set('album_id', $album_id);
            $this->set('type', $type);
        }
    } // upload

    public function edit () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $form = $this->params['form'];

        foreach ($form as $f=>$v) {
            $data = array();

            if (strpos($f, 'itle_')) {
                $id = (int) str_replace('title_', '', $f);

                if ($v) {
                    $data = array('title' => $v);
                }
                if ($form['desc_'.$id]) {
                    $data['description'] = $form['desc_'.$id];
                }
            }

            if (count($data) > 0) {
                $this->Image->read(null, $id);
                $this->Image->set($data);
                $this->Image->save();
            }
        }

        if ($form['album_id'] && isset($form['cover'])) {
            $this->loadModel('Album');
            $this->Album->id = $form['album_id'];
            $this->Album->saveField('image_id', $form['cover']);
        }

        $json = array(
            'status' => true,
            'mesg'   => __('Changes saved successfully.', true)
        );
        $this->response($json);
    } // edit

    public function remove () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $id   = $this->params['form']['id'];
        $data = $this->Image->read(array('album_id','filename'), $id);

        if (count($data) == 0) {
            $json = array(
                'status' => false,
                'error'  => __('Fail delete image, please try again.', true)
            );
            $this->response($json);
            return;
        }

        if (!$this->Image->deleteImage($id)) {
            $json = array(
                'status' => false,
                'error'  => __('Fail delete image, please try again.', true)
            );
            $this->response($json);
            return;
        }

        if ($data['Image']['album_id']) {
            $this->loadModel('Album');
            $this->Album->id = $data['Image']['album_id'];
            $type = $this->Album->field('type');
        } else {
            $type = 'slides';
        }

        $path = IMAGES.$type.DS;

        @unlink($path.$data['Image']['filename']);
        @unlink($path.'l_'.$data['Image']['filename']);
        @unlink($path.'s_'.$data['Image']['filename']);
        @unlink($path.'t_'.$data['Image']['filename']);

        $json = array('status' => true);
        $this->response($json);
    } // remove

    public function slides () {
        Configure::write('debug', 0);

        $data = $this->Image->find('all', array(
            'conditions' => array('Image.album_id' => 0),
            'fields'     => array('Image.filename', 'Image.description'),
            'order'      => array('Image.id DESC')
        ));

        if (count($data) > 0) {
                $xml  = '<cu3er><settings>' .
                        '<auto_play><defaults time="6" symbol="circular" /><tweenIn alpha="0" width="25" height="25" /><tweenOver alpha="0" tint="0xFFFFFF" /><tweenOut /></auto_play>' .
                        '<prev_button><defaults round_corners="25,25,25,25" /><tweenIn width="25" height="25" /><tweenOver tint="0xFFFFFF" scaleX="1.1" scaleY="1.1" /><tweenOut tint="0x000000" /></prev_button>' .
                        '<prev_symbol><defaults type="2" /><tweenIn scaleX="0.8" scaleY="0.5" /><tweenOver tint="0x000000" /></prev_symbol>' .
                        '<next_button><defaults round_corners="25,25,25,25" /><tweenIn width="25" height="25" /><tweenOver tint="0xFFFFFF" scaleX="1.1" scaleY="1.1" /><tweenOut tint="0x000000" /></next_button>' .
                        '<next_symbol><defaults type="2" /><tweenIn scaleX="0.8" scaleY="0.5" /><tweenOver tint="0x000000" /></next_symbol></settings><slides>';
                $path = $this->base.'/img/slides/';

                foreach ($data as $img) {
                    //$ttle = empty($img['title']) ? '' : '<b>'.$img['title'].'</b>';
                    //$desc = empty($img['description']) ? '' : '<div>'.$img['description'].'</div>';
                    $tran = '<transition num="3" slicing="horizontal" direction="left" shader="flat" duration="0.8" z_multiplier="2" delay="0.1" />';
                    $link = ($img['Image']['description']) ? '<link target="_self">'.$img['Image']['description'].'</link>' : '';
                    $xml .= $tran.'<slide><url>'.$path.$img['Image']['filename'].'</url>'.$link.'</slide>';
                }

                $xml .= '</slides></cu3er>';
        }

        $this->set('content', $xml);
        $this->render(false);
    } // slides

    public function axUpload () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        Configure::write('debug', 0);

        App::import('Vendor', 'Slide', array('file'=>'image.class.php'));

        $json = $this->params['form'];
        $name = basename($_FILES['uploadImage']['tmp_name']);

        list($width, $height, $mime,) = @getimagesize($_FILES['Filedata']['tmp_name']);

        $img = new Upload($_FILES['uploadImage']);

        $img->allowed            = array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
        $img->file_new_name_body = 's_'.$name;
        $img->image_min_width    = 64;
        $img->image_min_height   = 64;
        $img->image_x            = 180;
        $img->image_y            = 180;
        $img->image_ratio_crop   = true;
        $img->image_resize       = true;
        $img->Process(IMAGES.'slides'.DS);

        if ($img->processed) {
            $thumbnail = $img->file_dst_name;

            $img->file_new_name_body = $name;
            $img->image_x            = 830;
            $img->image_y            = 567;
            $img->image_ratio_crop   = true;
            $img->image_resize       = true;
            $img->Process(IMAGES.'slides'.DS);

            if ($img->processed) {
                $filename = $img->file_dst_name;
            } else {
                $json = array(
                    'status'  => -1,
                    'message' => __($img->error, true)
                );
            }
        } else {
            $json = array(
                'status'  => -1,
                'message' => __($img->error, true)
            );
        }
        $img->Clean();

        $data = array(
            'album_id' => 0,
            'filename' => $filename
        );

        if ($this->Image->save($data)) {
            $json = array(
                'status'    => 1,
                'id'        => $this->Image->id,
                'thumbnail' => $thumbnail
            );
        } else {
            $json = array(
                'status'  => -1,
                'message' => __('Error while insert slide record to database.', true)
            );
        }

        $this->set('json', $json);
        $this->render(false, 'json');
        sleep(1);
    } // axUpload

    public function manageSlides () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $data = $this->Image->find('all', array(
            'conditions' => array('Image.album_id' => 0),
            'order'      => array('Image.id DESC')
        ));

        $this->javascripts = am($this->javascripts, 'webtoolkit.aim');
        $this->pageTitle   = __('Manage Slides',true);
        $this->set('data', $data);
    } // manageSlides

    public function updateURL () {
        $form = $this->params['form'];

        foreach ($form as $k=>$v) {
            if (strpos($k, 'rl_')) {
                $id = str_replace('url_', '', $k);

                $this->Image->id = $id;
                $this->Image->saveField('description', $v);
            }
        }

        $this->Session->setFlash('<h4>'.__('Slides have been updated.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
        $this->redirect('/images/manageSlides');
    } // updateURL
} // ImagesController
?>